package org.groupg.practice.Compress;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.utils.IOUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.zip.GZIPInputStream;

public class TarGzExtractor {
    public static void extractTarGz(String inputFile, String outputDir) throws IOException {
        try (InputStream fi = Files.newInputStream(Paths.get(inputFile));
             GZIPInputStream gzi = new GZIPInputStream(fi);
             TarArchiveInputStream ti = new TarArchiveInputStream(gzi)) {

            TarArchiveEntry entry;
            while ((entry = ti.getNextTarEntry()) != null) {
                File outputFile = new File(outputDir, entry.getName());
                if (entry.isDirectory()) {
                    if (!outputFile.exists() && !outputFile.mkdirs()) {
                        throw new IOException("Failed to create directory: " + outputFile);
                    }
                } else {
                    File parent = outputFile.getParentFile();
                    if (!parent.exists() && !parent.mkdirs()) {
                        throw new IOException("Failed to create parent directory: " + parent);
                    }
                    try (OutputStream fo = Files.newOutputStream(outputFile.toPath())) {
                        IOUtils.copy(ti, fo);
                    }
                }
            }
        }
    }
}
